package com.sunny.l69;

/**
 *  Follow up for "Remove Duplicates":
 What if duplicates are allowed at most twice?

 For example,
 Given sorted array A =[1,1,1,2,2,3],

 Your function should return length =5, and A is now[1,1,2,2,3].
 */

/**
 * @Author zsunny
 * @Date 2018/9/22 9:32
 * @Mail zsunny@yeah.net
 */
public class Solution {
    public int removeDuplicates(int[] A) {
        if(null == A){
            return 0;
        }
        int len = A.length;
        if(0 == len)
            return len;
        int[] mind = new int[len];
        int tmpInd = 1;
        int tmp = 0;
        mind[0] = 0;
        for(int i=1; i<len; i++){
            if(A[i] == A[i-1]){
                tmp++;
                if(tmp > 1){
                    mind[i] = -1;
                }else{
                    mind[i] = tmpInd++;
                }
            }else{
                tmp = 0;
                mind[i] = tmpInd++;
            }
        }
        int res = 0;
        for(int i=0;i<mind.length;i++){
            if(mind[i] != -1) {
                res++;
                A[mind[i]] = A[i];
            }
        }
        return res;
    }
}
